#!/usr/bin/env python3
# Copyright (c) 2024 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0


import re
import argparse


def _get_rpm_dict(file):
    dic = {}
    with open(file, 'r', encoding="utf-8") as f:
        for line in f.readlines():
            line = line.strip()
            if line:
                name = re.findall("(.*)-[^-]+-[^-]+$", line)
                if name:
                    dic[name[0]] = line
    return dic


def do_compare(args):
    rpm_a_dic = _get_rpm_dict(args.file1)
    rpm_b_dic = _get_rpm_dict(args.file2)
    rpm_a_lst = sorted(rpm_a_dic.keys())
    rpm_b_lst = sorted(rpm_b_dic.keys())
    a_len, b_len = len(rpm_a_lst), len(rpm_b_lst)
    i = j = 0
    while True:
        if i < a_len:
            a_name = rpm_a_lst[i]
            if j < b_len:
                b_name = rpm_b_lst[j]
                if a_name == b_name:
                    if args.once:
                        if rpm_a_dic[a_name] != rpm_b_dic[b_name]:
                            print(f"{rpm_a_dic[a_name]},{rpm_b_dic[b_name]}")
                    else:
                        print(f"{rpm_a_dic[a_name]},{rpm_b_dic[b_name]}")
                    i += 1
                    j += 1
                elif a_name < b_name:
                    print(f"{rpm_a_dic[a_name]},")
                    i += 1
                else:
                    print(f",{rpm_b_dic[b_name]}")
                    j += 1
            else:
                print(f"{rpm_a_dic[a_name]},")
                i += 1
        else:
            if j < b_len:
                b_name = rpm_b_lst[j]
                print(f",{rpm_b_dic[b_name]}")
                j += 1
            else:
                break


def do_main(args):
    print("try -h/--help for more details.")


def main():
    parser = argparse.ArgumentParser(description="openEuler rpm package tool")
    parser.set_defaults(func=do_main)

    subparsers = parser.add_subparsers(help="package sub-commands")
    # compare
    subparser = subparsers.add_parser("compare", help="compare rpm between the two systems", aliases=["cmp"])
    # such as: https://mirrors.nju.edu.cn/openeuler/openEuler-20.03-LTS-SP4/everything/x86_64/Packages/
    subparser.add_argument("file1", type=str, help="rpm filename list file1")
    # such as: https://mirrors.nju.edu.cn/openeuler/openEuler-22.03-LTS-SP3/everything/x86_64/Packages/
    subparser.add_argument("file2", type=str, help="rpm filename list file2")
    subparser.add_argument("--once", action="store_true", help="remove duplicates")
    subparser.set_defaults(func=do_compare)

    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
